package metrics

import (
	"sync"
	"time"
	"xagent/internal/types"
)

// CollectorMetrics represents detailed metrics
type CollectorMetrics struct {
	Latencies map[string][]time.Duration
	Errors    map[string]int
	Tokens    map[string]int
}

// Collector collects system metrics
type Collector struct {
	metrics   map[string]*AgentMetrics
	latencies map[string][]time.Duration
	errors    map[string]int
	tokens    map[string]int
	mutex     sync.RWMutex
}

// NewCollector creates a new metrics collector
func NewCollector() *Collector {
	return &Collector{
		metrics:   make(map[string]*AgentMetrics),
		latencies: make(map[string][]time.Duration),
		errors:    make(map[string]int),
		tokens:    make(map[string]int),
	}
}

// RecordLatency records request latency
func (c *Collector) RecordLatency(provider string, duration time.Duration) {
	c.mutex.Lock()
	defer c.mutex.Unlock()

	// Initialize metrics for provider if not exists
	if _, ok := c.metrics[provider]; !ok {
		c.metrics[provider] = &AgentMetrics{
			RecentTasks: make([]*types.Task, 0),
		}
	}

	if _, ok := c.latencies[provider]; !ok {
		c.latencies[provider] = make([]time.Duration, 0)
	}
	c.latencies[provider] = append(c.latencies[provider], duration)
}

// RecordError records an error
func (c *Collector) RecordError(provider string) {
	c.mutex.Lock()
	defer c.mutex.Unlock()

	c.errors[provider]++
}

// RecordTokens records token usage
func (c *Collector) RecordTokens(provider string, count int) {
	c.mutex.Lock()
	defer c.mutex.Unlock()

	c.tokens[provider] += count
}

// GetMetrics returns current metrics
func (c *Collector) GetMetrics() map[string]interface{} {
	c.mutex.RLock()
	defer c.mutex.RUnlock()

	metrics := make(map[string]interface{})

	// Calculate average latencies
	avgLatencies := make(map[string]time.Duration)
	for provider, latencies := range c.latencies {
		var total time.Duration
		for _, lat := range latencies {
			total += lat
		}
		if len(latencies) > 0 {
			avgLatencies[provider] = total / time.Duration(len(latencies))
		}
	}

	metrics["latencies"] = avgLatencies
	metrics["errors"] = c.errors
	metrics["tokens"] = c.tokens

	return metrics
}

// RecordEvent records a metric event
func (c *Collector) RecordEvent(event string, data map[string]interface{}) error {
	// Implementation
	return nil
}
